package com.benshou.bsoa.common.filter;

import com.benshou.bsoa.common.trace.UserContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class UserContextFilter extends OncePerRequestFilter {

    public static final String HEAD_USER_ID = "X-User-Id";

    public static final String HEAD_USER_COMP_ID = "X-User-Comp-Id";

    public static final String HEAD_USER_DEPT_ID = "X-User-Dept-Id";

    public static final String HEAD_USER_ROLE_IDS = "X-User-Role-Ids";

    public static final String HEAD_CLIENT_TIMEZONE = "X-Client-Timezone";

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            @NotNull HttpServletResponse response,
            @NotNull FilterChain filterChain
    ) throws ServletException, IOException {
        try {
            // 从请求头获取用户信息
            String userId = request.getHeader(HEAD_USER_ID);
            String userCompId = request.getHeader(HEAD_USER_COMP_ID);
            String userDeptId = request.getHeader(HEAD_USER_DEPT_ID);
            String userRoleIds = request.getHeader(HEAD_USER_ROLE_IDS);
            String clientTimezone = request.getHeader(HEAD_CLIENT_TIMEZONE);

            // 设置到UserContext中，增加非空检查，防御性编程
            if (userId != null && !userId.isEmpty()) {
                UserContext.setUserId(userId);
            }
            if (userCompId != null && !userCompId.isEmpty()) {
                UserContext.setUserCompId(userCompId);
            }
            if (userDeptId != null && !userDeptId.isEmpty()) {
                UserContext.setUserDeptId(userDeptId);
            }
            if (userRoleIds != null && !userRoleIds.isEmpty()) {
                UserContext.setUserRoleIds(userRoleIds);
            }
            if (clientTimezone != null && !clientTimezone.isEmpty()) {
                UserContext.setClientTimezone(clientTimezone);
            }

            filterChain.doFilter(request, response);
        } finally {
            // 清理用户上下文
            UserContext.clear();
        }
    }
}